<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * Created by PhpStorm.
 * User: 张旭
 * Date: 2020/8/12
 * Time: 9:35
 */


use think\Db;

// 数据处理类
/**
 * 新增数据
 * @param $name
 * @param $data
 * @param int $type 1直接插入   2插入后返回新增ID  3批量插入数据
 */
function insertData($name, $data, $type = 1)
{
    if ($type == 1) {
        Db::name($name)->insert($data);
        ajaxMsg(1, '新增成功');
    } elseif ($type == 2) {
        $id = Db::name($name)->insertGetId($data);
        ajaxMsg(1, $id, 2);
    } else {
        Db::name($name)->insertAll($data);
        ajaxMsg(1, '新增成功,本次新增' . sizeof($data) . '条数据');
    }
}

/**
 * 判断文件是否存在后，删除
 * @param $path
 * @return bool
 * @return boolean
 * @author byron sampson <xiaobo.sun@qq.com>
 */
function new_unlink($path)
{
    return is_file($path) && unlink($path);
}

/**
 * 单条数据更新
 * @param $name
 * @param $where
 * @param $data
 * @return int|string
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function upDate($name, $where, $data)
{
    return Db::name($name)->where($where)->update($data);
}

function array_to_lower($weChatArr)
    {
        foreach ($weChatArr as $key => $weChat) {
            $byteArr2D[] = str_split(trim($weChat));
            foreach ($byteArr2D[$key] as $byte) {
                $byteToLowerArr2D[$key][] = ord($byte) >= 65 && ord($byte) <= 90 ? chr(ord($byte) + 32) : $byte;
            }
        }
        return array_map('implode', $byteToLowerArr2D);
    }

/**
 * 单条数据查询
 * @param $name
 * @param array $where
 * @return array|PDOStatement|string|\think\Model|null
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function findData($name, $where)
{
    return Db::name($name)->where($where)->find();
}

/**
 * 单表多查
 * @param $name
 * @param array $where
 * @param string $field
 * @param int $page
 * @param int $type
 * @return array|PDOStatement|string|\think\Collection|\think\model\Collection|\think\Paginator
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function selectData($name, $where = [], $field = '*', $page = 10, $type = 1)
{
    if ($type == 1) {
        return Db::name($name)->where($where)->field($field)->select();
    }
    return Db::name($name)->where($where)->field($field)->paginate($page, false, ['query' => request()->param()]);
}


/**
 * 多表联查
 * @param array $table
 * @param array $where
 * @param string $field
 * @param int $page
 * @param int $type
 * @return array|PDOStatement|string|\think\Collection|\think\model\Collection|\think\Paginator
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function selectMoreTable($table = [], $where = [], $field = '*', $page = 10, $type = 1)
{
    if ($type == 1) {
        $data = Db::field($field)->table($table)->where($where)->select();
        return $data;
    }
    $data = Db::field($field)
        ->table($table)
        ->where($where)
        ->paginate($page, false, ['query' => request()->param()]);

    return $data;
}

/**
 * 删除数据
 * @param $name
 * @param $where
 * @return int
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function delData($name, $where)
{
    return Db::name($name)->where($where)->delete();
}


//递归分类
function getTree($array, $pid = 0, $level = 0)
{

    //声明静态数组,避免递归调用时,多次声明导致数组覆盖
    static $list = [];
    foreach ($array as $key => $value) {
        //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
        if ($value['pid'] == $pid) {
            //父节点为根节点的节点,级别为0，也就是第一级
            $value['level'] = $level;
            //把数组放到list中
            $list[] = $value;
            //把这个节点从数组中移除,减少后续递归消耗
            unset($array[$key]);
            //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
            getTree($array, $value['id'], $level + 1);

        }
    }
    return $list;
}

/**
 * 返回结构化递归数据
 * @param $array
 */
function getTrees($array)
{
    $array = getTree($array);
    foreach ($array as $key => $value) {
        $array[$key]['title'] = str_repeat('&nbsp;&nbsp;&nbsp;', $value['level']) . str_repeat('-----', $value['level']) . '├ ' . $array[$key]['title'];
    }
    return $array;
}

/**
 * 数组分组
 * @param $dataArr
 * @param $keyStr
 * @return array
 */
function dataGroup($dataArr, $keyStr)
{
    $newArr = [];
    foreach ($dataArr as $k => $val) {
        $newArr[$val[$keyStr]][] = $val;
    }
    return array_values($newArr);
}


//杂项规整类

/**
 * 文件上传
 * @param $file //接收的文件
 * @param array $validate 验证文件大小,格式等,详见tp5.1文档
 * @param $savePath //保存路径
 * @return array
 */
function Upload($file, $validate = [], $savePath)
{
    //将文件保存到public/uploads目录下面
    $info = $file->validate($validate)->move('../public' . $savePath);
    if ($info) {
        //获取上传到后台的文件名
        $fileName = $info->getSaveName();
        //获取文件路径
        $filePath = 'http://' . $_SERVER['SERVER_NAME'] . $savePath . $fileName;
        //获取文件后缀
        $suffix = $info->getExtension();
        //返回格式,路径
        $data = ['code' => '1', 'suffix' => $suffix, 'filePath' => $filePath, 'filename' => $fileName];
        return $data;
    } else {
        $data = ['code' => 0, 'msg' => '文件过大或格式不正确导致上传失败'];
        return $data;
    }
}


/**
 * 以json类型返回信息
 * @param int $status
 * @param string $msg
 * @param int $type 1返回后阻断程序   2返回结果不阻断程序
 */
function ajaxMsg($status = 1, $msg = '', $type = 1)
{
    if ($type == 1) {
        exit(json_encode(['status' => $status, 'msg' => $msg]));
    } else {
        return json_encode(['status' => $status, 'msg' => $msg]);
    }

}

function ajaxMsgcontent($status = 1, $msg = '', $content = '', $type = 1)
{
    if ($type == 1) {
        exit(json_encode(['status' => $status, 'msg' => $msg, 'content' => $content]));
    } else {
        return json_encode(['status' => $status, 'msg' => $msg, 'content' => $content]);
    }

}

/**
 * 获取请求Ip
 * @return array|false|string
 */
function getIp()
{
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow:未知的Ip";

    return $ip;
}


/**
 * @description excel数据导出方法封装 列数支持700+
 * @param array $title 列标题、宽度和数据字段 二维数组  必须 array(array('title'='name','width'=>30,'field'=>'user_name'),array('title'='sex','width'=>10,'field'=>'sex'))
 * @param array $data 二维数组数据
 * @param string $fileName 导出文件名
 * @param bool $bold 列标题是否加粗
 * @param bool $returnFile 是否保存为文件
 */

function exportDataToExcel($title = array(), $data = array(), $fileName = '', $bold = true, $returnFile = false)
{
    require_once '../vendor/PHPExcel/PHPExcel.php';

    if (empty($title)) {
        return false;
    }
    $objPHPExcel = new \PHPExcel();
    $count = count($title);

    for ($i = 0; $i < $count; $i++) {
        $i_name = PHPExcel_Cell::stringFromColumnIndex($i);//处理列大于26个的方法
        //设置列宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension($i_name)->setWidth($title[$i]['width']);
        //设置列名
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . '1', $title[$i]['title']);
        //列名是否加粗
        if ($bold) {
            $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->getFont()->setBold(true);
        }


        //数据处理
        if ($data) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . '2', $data[$i]['op']);
        }
    }

    $objPHPExcel->getActiveSheet()->setTitle('Simple');
    $objPHPExcel->setActiveSheetIndex(0);
    $fileName = $fileName ? $fileName : date("Ymd", time()) . rand(1111, 9999) . '.xlsx';
    if ($returnFile) {
        $dirPath = '/';//注意要设置为绝对路径
        $newFileName = date('YmdHis') . mt_rand(1111, 9999) . '_' . $fileName;
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($dirPath . '/' . $newFileName);
        return $newFileName;
    } else {
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Access-Control-Expose-Headers: Content-Disposition');
        header('Content-Disposition: attachment;filename=' . $fileName);
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }


}

function exportAllDataToExcel($title = array(), $data = array(), $fileName = '', $bold = true, $returnFile = false)
{
    require_once '../vendor/PHPExcel/PHPExcel.php';

    if (empty($title)) {
        return false;
    }
    $objPHPExcel = new \PHPExcel();
    $count = count($title);

    for ($i = 0; $i < $count; $i++) {
        $i_name = PHPExcel_Cell::stringFromColumnIndex($i);//处理列大于26个的方法
        //设置列宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension($i_name)->setWidth($title[$i]['width']);
        //设置列名
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . '1', $title[$i]['title']);
        //列名是否加粗
        if ($bold) {
            $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->getFont()->setBold(true);
        }


        //数据处理
        if ($data) {
            foreach ($data as $key => $val) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . ($key + 2), $val[$i]['op']);
            }

        }

    }

    $objPHPExcel->getActiveSheet()->setTitle('Simple');
    $objPHPExcel->setActiveSheetIndex(0);
    $fileName = $fileName ? $fileName : date("Ymd", time()) . rand(1111, 9999) . '.xlsx';
    if ($returnFile) {
        $dirPath = '/';//注意要设置为绝对路径
        $newFileName = date('YmdHis') . mt_rand(1111, 9999) . '_' . $fileName;
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($dirPath . '/' . $newFileName);
        return $newFileName;
    } else {
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Access-Control-Expose-Headers: Content-Disposition');
        header('Content-Disposition: attachment;filename=' . $fileName);
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }


}

function exportAllDataToExcels($title = array(), $data = array(), $fileName = '', $bold = true, $returnFile = false)
{
    require_once '../vendor/PHPExcel/PHPExcel.php';

    if (empty($title)) {
        return false;
    }
    $objPHPExcel = new \PHPExcel();
    $count = count($title);

    for ($i = 0; $i < $count; $i++) {
        $i_name = PHPExcel_Cell::stringFromColumnIndex($i);//处理列大于26个的方法
        //设置列宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension($i_name)->setWidth($title[$i]['width']);
        //设置列名
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . '1', $title[$i]['title']);
        //列名是否加粗
        if ($bold) {
            $objPHPExcel->getActiveSheet()->getStyle($i_name . '1')->getFont()->setBold(true);
        }


        //数据处理
        if ($data) {
            foreach ($data as $key => $val) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($i_name . ($key + 2), $val[$i]);
            }

        }

    }

    $objPHPExcel->getActiveSheet()->setTitle('Simple');
    $objPHPExcel->setActiveSheetIndex(0);
    $fileName = $fileName ? $fileName : date("Ymd", time()) . rand(1111, 9999) . '.xlsx';
    if ($returnFile) {
        $dirPath = '/';//注意要设置为绝对路径
        $newFileName = date('YmdHis') . mt_rand(1111, 9999) . '_' . $fileName;
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($dirPath . '/' . $newFileName);
        return $newFileName;
    } else {
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Access-Control-Expose-Headers: Content-Disposition');
        header('Content-Disposition: attachment;filename=' . $fileName);
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }


}
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
function sendMsg($mobile,$code){
//这里的路径EXTEND_PATH就是指tp5根目录下的extend目录，系统自带常量。alisms为我们复制api_sdk过来后更改的目录名称
    require_once '../extend/alisms/vendor/autoload.php';
    Config::load();             //加载区域结点配置
    $accessKeyId = 'LTAI4FfHHqeCiaVpmTTgpWRb';  //阿里云短信获取的accessKeyId
    $accessKeySecret = '70wV0nR1OfdTZTlZgv5GBRubtq0RQM';    //阿里云短信获取的accessKeySecret
//这个个是审核过的模板内容中的变量赋值，记住数组中字符串code要和模板内容中的保持一致
//比如我们模板中的内容为：你的验证码为：${code}，该验证码5分钟内有效，请勿泄漏！
    $templateParam = $code;           //模板变量替换
    $signName = '科立尔科技'; //这个是短信签名，要审核通过
    $templateCode = 'SMS_171350741';   //短信模板ID，记得要审核通过的
//短信API产品名（短信产品名固定，无需修改）
    $product = "Dysmsapi";
//短信API产品域名（接口地址固定，无需修改）
    $domain = "dysmsapi.aliyuncs.com";
//暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
    $region = "cn-hangzhou";
// 初始化用户Profile实例
    $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
// 增加服务结点
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
// 初始化AcsClient用于发起请求
    $acsClient= new DefaultAcsClient($profile);
// 初始化SendSmsRequest实例用于设置发送短信的参数
    $request = new SendSmsRequest();
// 必填，设置雉短信接收号码
    $request->setPhoneNumbers($mobile);
// 必填，设置签名名称
    $request->setSignName($signName);
// 必填，设置模板CODE
    $request->setTemplateCode($templateCode);
// 可选，设置模板参数
    if($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }
//发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);
//返回请求结果
    $result = json_decode(json_encode($acsResponse),true);
    return $result;
}
 function getstatus($type,$status){
      $des = '';
      if($type == '学校审核'){
          switch ($status) {
              case '1':
                  // code...
                  $des = '待审核';
                  break;
              case '2':
                  // code...
                  $des = '拒绝';
                  break;
              case '3':
                  // code...
                  $des = '审核通过';
                  break;
              case '4':
                  // code...
                  $des = '错误';
                  break;
              case '5':
                  // code...
                  $des = '错误';
                  break;
              case '6':
                  // code...
                  $des = '审核通过';
                  break;
              case '7':
                  // code...
                  $des = '审核通过';
                  break;
              default:
                  // code...
                  break;
          }
      }else if($type=="教委审核"){
          switch ($status) {
              case '1':
                  // code...
                  $des = '错误';
                  break;
              case '2':
                  // code...
                  $des = '错误';
                  break;
              case '3':
                  // code...
                  $des = '审核通过';
                  break;
              case '4':
                  // code...
                  $des = '待审核';
                  break;
              case '5':
                  // code...
                  $des = '拒绝';
                  break;
              case '6':
                  // code...
                  $des = '审核通过';
                  break;
              case '7':
                  // code...
                  $des = '审核通过';
                  break;
              default:
                  // code...
                  break;
          }          
      }else if($type=="中心审核"){
          switch ($status) {
              case '1':
                  // code...
                  $des = '待审核';
                  break;
              case '2':
                  // code...
                  $des = '待审核';
                  break;
              case '3':
                  // code...
                  $des = '待审核';
                  break;
              case '4':
                  // code...
                  $des = '待审核';
                  break;
              case '5':
                  // code...
                  $des = '待审核';
                  break;
              case '6':
                  // code...
                  $des = '审核通过';
                  break;
              case '7':
                  // code...
                  $des = "拒绝";
                  break;
              default:
                  // code...
                  break;
          }  
      }
      return $des;
  }
  function Sec2Time($time){
        if(is_numeric($time)){
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if($time >= 31556926){
                $value["years"] = floor($time/31556926);
                $time = ($time%31556926);
            }
            if($time >= 86400){
                $value["days"] = floor($time/86400);
                $time = ($time%86400);
            }
            if($time >= 3600){
                $value["hours"] = floor($time/3600);
                $time = ($time%3600);
            }
            if($time >= 60){
                $value["minutes"] = floor($time/60);
                $time = ($time%60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t=$value["years"] ."年". $value["days"] ."天";
            Return $t;

        }else{
            return (bool) FALSE;
        }
    }